define(function (require) {
	//require('security');
	//app.useModule('security');
	require('arcgis_analysis');
	require(['echarts'], function (es) {
		echartsObject.hasInitFinsh = true;
		echartsObject.es = es;
		if (echartsObject.initFinshEvent) {
			echartsObject.initFinshEvent.forEach(function (e) {
				e(es);
			});
		}
	});

	require('echarts-pie');

	require(['plupload', 'plupload.queue', 'plupload.i18n'], function () {

	});
	require('ui-upload');

	var app = require('app');
	app.useModule('echarts.pie');
	app.useModule('arcgis.analysis');
	app.useModule('ui.upload');
	//app.useModule('ui.as.files');

	app.filter("numlen", function () {
		return function (input, length) {
			if (input == null || input == '' || input == "undefined") return input;
			if (!isNaN(input)) {
				if (input == parseInt(input) || input > 10000) {
					return input;
				}

				if (length == null) length = 4;
				var n = Number(input);
				n = n.toFixed(length);
				n = Number(n);

				return n;
			} else {
				return input;
			}
		};
	});


	app.controller('analysis_Ctrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
		$rootScope.filterField = function (fn) {
			return $rootScope[fn].selectedRow['id'];
			//return f_rcode.mid;
		};

		$scope.initAnalysisLayer = function () {
			$rootScope.analysisLayer = {};
			$rootScope.analysisLayer.selectedRow = {};
			$rootScope.analysisLayer.selectedRow.url = getQueryZyUrl();
			$rootScope.analysisLayer.selectedRow.id = "2d85b4982316406ba53d0c4d28ddc1e9";
			$rootScope.analysisLayer.selectedRow.medname = "ldzy2017";
			$rootScope.analysisLayer.selectedRow.type = "ArcGISDynamicMapServiceLayer";
			$rootScope.analysisLayer.selectedRow.queryLayerId = 0;
			//$scope.onchangeAnalysisLayer();
			$rootScope.set2DLayersShow('林地资源',true);//控制林地资源图层显示
		};



		/**
		 * gis中的pagesize记录被选中时的效果
		 */
		$scope.gisListSelectObject = function (list, row) {
			if (list == null || list.length < 1) return;
			if (row == null) row = list[0];
			var selected = !row.selected;
			for (var k = 0; k < list.length; k++) {
				list[k]["selected"] = false;
			};
			row["selected"] = selected;
			return;
		};



		/**
		 * 数据分析功能，解析参数，创建分析功能
		 */
		$scope.validDrawAnalysisParan = function (analysisFunction) {

			if ($rootScope.analysisGeometry == null) {
				$.messager.alert("系统提示", "请先绘制图形");
				return
			}
			$scope.validCommonAnalysisParan(analysisFunction);
		};
		/**
		 * 数据分析功能，解析参数，创建分析功能
		 */
		$scope.validGpsAnalysisParan = function (analysisFunction) {

			if (window.FileReader) {
				var file = document.getElementById("fileField_dj").files[0];
				if (file == null) {
					$.messager.alert("系统提示", "请先导入gps文件");
					return;
				}
			} //支持IE 7 8 9 10
			else if (typeof window.ActiveXObject != 'undefined') {
				//得不到正确的路径   处理了一下
				var fil = document.getElementById("fileField_dj");
				fil.select();
				window.parent.document.body.focus();
				var filePath = document.selection.createRange().text;
				if (filePath == "") {
					$.messager.alert("系统提示", "请选择GPS数据文件！");
					return;
				}
			} else if (document.implementation && document.implementation.createDocument) {
				var xmlDoc;
				xmlDoc = document.implementation.createDocument("", "", null);
				xmlDoc.async = false;
				xmlDoc.load(document.getElementById("fileField_dj").value);
				if (xmlDoc.xml == null || xmlDoc.xml == 'undefined') {
					$.messager.alert("系统提示", "请选择GPS数据文件！");
					return;
				}
			} else {
				$.messager.alert("系统提示", "error");
				return;
			}
			$scope.validCommonAnalysisParan(analysisFunction);
		};

		$scope.analysisLayers = {};//分析图层信息
		$scope.analysisSid = null;//分析图层的id
		$scope.selectSid = null;//选中图层的id

		/**
		 * 用户自定义选图
		 * @return {[type]} [description]
		 */
		$scope.selectUserGeomety = function () {
			if ($scope.selectSid == null) {
				$.messager.alert("系统提示", "请先选择选图图层");
				return;
			}
			var sl = $scope.xtLayer.selectedRow;
			//$scope.analysisLayers[$scope.selectSid].hide();
			$rootScope.analysisSelectGeomety(sl.url, [sl.queryLayerId], function (results) {
				if ($scope.selectSid != null && $scope.selectSid != $scope.analysisSid) {
					//$scope.analysisLayers[$scope.selectSid].hide();
				}
			});
		}


		/**
		 * 取图方式变化时，隐藏选图图层
		 * @return {[type]} [description]
		 */
		$scope.onchangemethod = function () {
			if ($scope.selectSid != null && $scope.selectSid != $scope.analysisSid) {
				$scope.analysisLayers[$scope.selectSid].hide();
			}
		};

		$scope.onchangeselectmethod = function () {
			if ($scope.selectSid != null && $scope.selectSid != $scope.analysisSid) {
				$scope.analysisLayers[$scope.selectSid].show();
			}
		};


		/**
		 * 取图图层变化时，重新显示图层，添加地图服务，显示图层不显示
		 */
		$rootScope.onchangeXtLayer = function () {
			setTimeout(function () {
				var sl = $scope.xtLayer.selectedRow;
				if (sl == null) return;

				var csid = sl.id;

				if ($scope.selectSid != null && $scope.selectSid != $scope.analysisSid) {
					$scope.analysisLayers[$scope.selectSid].hide();
				}

				if ($scope.analysisLayers[csid] == null) {
					var mapLayer = $rootScope.addLayer(sl.url, sl.type, null, null, true);
					if (mapLayer == null) {
						$.messager.alert("系统提示", "地图服务配置错误");
						return;
					} else {
						$scope.selectSid = csid;
						//mapLayer.hide();
						$scope.analysisLayers[csid] = mapLayer;
					}
				} else {
					$scope.selectSid = csid;
					$scope.analysisLayers[csid].show();
				}
			}, 300);
		};

		/**
		 * 分析图层变化时，重新处理图层问题
		 */
		$rootScope.onchangeAnalysisLayer = function () {
			setTimeout(function () {
				var sl = $scope.analysisLayer.selectedRow;
				if (sl == null) return;

				var csid = sl.id;

				if ($scope.analysisSid != null && $scope.analysisSid != $scope.selectSid) {
					$scope.analysisLayers[$scope.analysisSid].hide();
				}

				if ($scope.analysisLayers[csid] != null) {
					$scope.analysisSid = csid;
					$scope.analysisLayers[csid].show();
				} else {
					var mapLayer = $rootScope.addLayer(sl.url, sl.type, null, null, true);
					if (mapLayer == null) {
						$.messager.alert("系统提示", "地图服务配置错误");
						return;
					} else {
						$scope.analysisSid = csid;
						$scope.analysisLayers[csid] = mapLayer;
					}
				}
			}, 300);
		};

		/**
		 * [通用的数据检查功能]
		 * @param  {[type]} analysisFunction [description]
		 * @return {[type]}                  [description]
		 */
		$scope.validCommonAnalysisParan = function (analysisFunction) {
			var sl = $scope.analysisLayer.selectedRow;

			if (sl == null) {
				$.messager.alert("系统提示", "请先选择分析图层");
				return;
			}

			var tjlb = $scope.tjlbSearch.selectedRow;
			if (tjlb == null) {
				$.messager.alert("系统提示", "请先选择统计类别");
				return;
			} else {
				$scope.analysisKeyFieldAlsia = tjlb.aliasName;
				$scope.analysisKeyField = tjlb.name;
			}

			var tjfl = $scope.tjfieldSearch.selectedRow;

			if (tjfl == null) {
				$.messager.alert("系统提示", "请先选择统计字段");
				return;
			}
			var field = {};
			field.field = tjfl.name;
			field.Alias = tjfl.aliasName;

			var fields = [];
			fields.push(field);
			$scope.analysisResultField = fields;


			if ($scope.analysisLayerBufferDistance == null) {
				$.messager.alert("系统提示", "请先设置缓冲区大小！");
				return;
			}
			//构造显示函数
			var mustdic = false;
			if (sl.medname != null && sl.medname != '') {
				mustdic = true;
			}
			var analysisUrl = sl.url + "/" + sl.queryLayerId;
			$rootScope.initAnalysisParam(analysisUrl, sl.name, 'OBJECTID',
				tjlb.name, tjlb.aliasName,
				fields,
				[$scope.analysisLayerBufferDistance],
				sl.medname, null, mustdic,
				$scope.showAnalysisResult);
			analysisFunction();

		};

		/**
		 * 获取显示字段问题
		 * @param {Object} id
		 * @param {Object} oncomplete
		 * @param {Object} error
		 */
		$scope.getShowFieldInfo = function (id, oncomplete, error) {
			$rootScope.formInit('analShowfield', {
				keyField: 'id',
				randomFields: ['id']
			});
			$rootScope.analShowfield.queryObject["pid:="] = id;
			$rootScope.analShowfield.orderObject["order"] = 0;
			$rootScope.loadData('analShowfield', function (fn, data) {
				if (oncomplete) {
					oncomplete(data);
				}
			}, function (e) {
				error(e);
			});
		};

		/**
		 * 依据数据进行数据字典转换
		 * @param  {[type]} list       [description]
		 * @param  {[type]} dicname    [description]
		 * @param  {[type]} rooturl    [description]
		 * @param  {[type]} oncomplete [description]
		 * @return {[type]}            [description]
		 */
		$scope.getFieldInfo = function (dicname, rooturl, convert, oncomplete, error) {
			if (convert == null) {
				convert = false;
			}

			if (convert) {
				if (rooturl == null) {
					rooturl = getServerBaseUrl();
				}
				var url = rooturl + "/metadata/getEntitys/" + dicname;
				$.ajax({
					url: url,
					type: 'POST',
					data: {},
					timeout: 35000,
					dataType: 'json',
					success: function (data) {
						if (oncomplete) {
							oncomplete(data);
						}
					},
					error: function (e) {
						if (error) {
							error(e);
						}
					}
				});
			} else {
				if (oncomplete) {
					oncomplete(null);
				}
			}
		};

		$scope.fieldinfo = null;//字典信息

		/**
		 * 统计信息梳理
		 */
		$scope.analysisTjlbGather = function () {
			var gatheranalysisFeaturesResult = $rootScope.getAlysisFeaturesResult();
			var gatherarcgisAnalysisObejct = $rootScope.getArcgisAnalysisObejct();
			if (gatheranalysisFeaturesResult == null) {
				$.messager.alert("系统提示", "分析失败");
				return;
			} else {
				var temp = [];
				for (var k = 0; k < gatheranalysisFeaturesResult.length; k++) {
					var o_feature = gatheranalysisFeaturesResult[k];
					var value = o_feature.attributes["DI_LEI"];

					//非林业部门管理林地和非林地，其中20表示非林业部门管理林地
					var gllx = o_feature.attributes["GLLX"];
					if ("20" == gllx || 20 == gllx) continue;
					if ("0200" == value) {
						continue;
					}
					temp.push(o_feature);
				}
				gatheranalysisFeaturesResult = temp;
				//$arcgis_analysis.analysisFeaturesResult=temp;

				var result = {};
				var resultLst = [];
				for (var k = 0; k < gatheranalysisFeaturesResult.length; k++) {
					var o_feature = gatheranalysisFeaturesResult[k];
					console.log("feature:" + k);
					console.log(o_feature);
					var value = o_feature.attributes[gatherarcgisAnalysisObejct.classificationField];

					if (value == null || value == "undefined") {
						value = "";
					}

					if (result[value] != null) {
						var tempValue = result[value];
						var itemValue = jQuery.extend(true, {}, tempValue);
						for (var j = gatherarcgisAnalysisObejct.resultField.length - 1; j > -1; j--) {

							var countValue = 0;
							if (gatherarcgisAnalysisObejct.resultField[j].field == "MIAN_JI") {
								countValue = o_feature.attributes["ArcgisComputerArea"] * 100;//保留单位
							} else {
								countValue = o_feature.attributes[gatherarcgisAnalysisObejct.resultField[j].field] *
									o_feature.attributes['Valuepercentage'];

								console.log("小班号：" + o_feature.attributes["DI_JI_HAO"]);
								console.log("小班计算展示合计统计值计算" + o_feature.attributes[gatherarcgisAnalysisObejct.resultField[j].field] + "*" + o_feature.attributes['Valuepercentage'] + "=" + countValue);

							}
							itemValue[gatherarcgisAnalysisObejct.resultField[j].field] += countValue;
						}
						result[value] = itemValue;
					} else {
						//result[value]=true;
						var itemValue = { key: value };
						for (var j = gatherarcgisAnalysisObejct.resultField.length - 1; j > -1; j--) {

							var countValue = 0;
							if (gatherarcgisAnalysisObejct.resultField[j].field == "MIAN_JI") {
								countValue = o_feature.attributes["ArcgisComputerArea"] * 100;//保留单位
							} else {
								countValue = o_feature.attributes[gatherarcgisAnalysisObejct.resultField[j].field] *
									o_feature.attributes['Valuepercentage'];

								console.log("小班号：" + o_feature.attributes["DI_JI_HAO"]);
								console.log("小班计算展示合计统计值计算" + o_feature.attributes[gatherarcgisAnalysisObejct.resultField[j].field] + "*" + o_feature.attributes['Valuepercentage'] + "=" + countValue);

							}

							/*var o_count_value=o_feature.attributes[gatherarcgisAnalysisObejct.resultField[j].field];
							var Valuepercentage=o_feature.attributes['Valuepercentage'];
							
							
							var countValue=o_feature.attributes[gatherarcgisAnalysisObejct.resultField[j].field]*
								o_feature.attributes['Valuepercentage'];
							console.log("小班号："+o_feature.attributes["DI_JI_HAO"]);
							console.log("小班计算数据展示统计值计算"+o_feature.attributes[gatherarcgisAnalysisObejct.resultField[j].field]+"*"+o_feature.attributes['Valuepercentage']+"="+countValue);
							*/
							itemValue[gatherarcgisAnalysisObejct.resultField[j].field] = countValue;
						}
						result[value] = itemValue;
						resultLst.push(value);
					}
				}
				console.log("数据展示:");
				console.log(result);
				var lresult = {};
				lresult.keyLst = resultLst;//结果主键值
				lresult.keyResult = result;//查询结果信息

				//lresult.queryXbLst=$scope.classificationStatistics();

				return lresult;
				/*if($arcgis_analysis.showAnalysisResult!=null){
					$arcgis_analysis.showAnalysisResult($arcgis_analysis.analysisResult);
				}*/
			}
		};
		/**
		 * 修改展示效果（数据分析功能）
		 */
		$scope.showAnalysisResult = function (oresult) {

			var sl = $scope.analysisLayer.selectedRow;
			var convert = false;
			if (sl.medname != null && sl.medname != '') {
				convert = true;
			}

			var result = $scope.analysisTjlbGather();

			if (oresult.queryXbLst != null) {
				var tempqueryXbLst = [];

				for (var k = 0; k < oresult.queryXbLst.length; k++) {
					var o_feature = oresult.queryXbLst[k];
					var value = o_feature.attributes["DI_LEI"];

					//非林业部门管理林地和非林地，其中20表示非林业部门管理林地
					var gllx = o_feature.attributes["GLLX"];
					if ("20" == gllx || 20 == gllx) continue;
					if ("0200" == value) {
						continue;
					}
					/*if("0200"==value){
						continue;
					}*/

					tempqueryXbLst.push(o_feature);
				}
				result.queryXbLst = tempqueryXbLst;

			} else {
				result.queryXbLst = [];
			}
			//result=oresult;

			//$scope.getFieldInfo(sl.medname,null,convert,function(list){
			$scope.getShowFieldInfo(sl.id, function (list) {

				/*$scope.$apply(function(){*/
				$scope.setSearchOpen(false);
				var analysisShowResult = {};
				analysisShowResult.legendlst = [];
				var data = [];

				$scope.tableResult = [];
				for (var k = 0; k < result.keyLst.length; k++) {
					var key = result.keyLst[k];
					var item = {};
					item.name = key;
					var fieldDesc = $scope.analysisKeyField + "_DESC";
					for (var j = 0; j < result.queryXbLst.length; j++) {
						if (result.queryXbLst[j].attributes[$scope.analysisKeyField] == key
							&& result.queryXbLst[j].attributes[fieldDesc] != null
							&& result.queryXbLst[j].attributes[fieldDesc] != '') {
							item.name = result.queryXbLst[j].attributes[fieldDesc];
							break;
						}
					}

					var ivalue = result.keyResult[key][$scope.analysisResultField[0].field];
					if (!isNaN(ivalue)) {
						ivalue = Number(ivalue);
						ivalue = ivalue.toFixed(4);
						ivalue = Number(ivalue);
					}

					item.value = ivalue;//数据分析字段
					data.push(item);
					analysisShowResult.legendlst.push(item.name);

					var tableItem = {};
					tableItem[$scope.analysisKeyFieldAlsia] = item.name;
					for (var j = 0; j < $scope.analysisResultField.length; j++) {
						var kvalue = result.keyResult[key][$scope.analysisResultField[j].field];
						if (!isNaN(kvalue)) {
							kvalue = Number(kvalue);
							kvalue = kvalue.toFixed(4);
							kvalue = Number(kvalue);
						}
						tableItem[$scope.analysisResultField[j].Alias] = kvalue;//数据分析字段
					}

					$scope.tableResult.push(tableItem);
				}
				analysisShowResult.data = data;
				$scope.analysisShowResult = $.extend(true, {}, analysisShowResult);
				$scope.resultXb = result.queryXbLst;

				$rootScope.resultXbTest = result.queryXbLst;

				var fieldinfo = [];
				if (list == null || list.length < 1) {
					for (var key in $scope.resultXb[0].attributes) {
						if (key != 'ArcgisComputerArea'
							&& key != 'ArcgisQueryFeatureComputerArea'
							&& key != 'Valuepercentage') {
							var field = {};
							field.alias = key;
							field.name = key;
							fieldinfo.push(field);
						}

					}

				} else {
					for (var k = 0; k < list.length; k++) {
						var item = list[k];
						var field = {};
						field.alias = item.aliasName;
						if (item.dictionaryName != null
							&& item.dictionaryName != ''
							&& item.dictionaryName != 'undefined') {
							field.name = item.name + "_DESC";
						} else {
							field.name = item.name;
						}
						field.selected = true;
						fieldinfo.push(field);

					}

				}
				/*					var field_ArcgisComputerArea={};
									field_ArcgisComputerArea.alias='压占面积';
									field_ArcgisComputerArea.name='ArcgisComputerArea';
									field_ArcgisComputerArea.selected=true;
									fieldinfo.push(field_ArcgisComputerArea);
				
									var field_Valuepercentage={};
									field_Valuepercentage.alias='压占比';
									field_Valuepercentage.name='Valuepercentage';
									field_Valuepercentage.selected=true;
									fieldinfo.push(field_Valuepercentage);
				
									var field_ArcgisQueryFeatureComputerArea={};
									field_ArcgisQueryFeatureComputerArea.alias='小班计算面积';
									field_ArcgisQueryFeatureComputerArea.name='ArcgisQueryFeatureComputerArea';
									field_ArcgisQueryFeatureComputerArea.selected=true;
									fieldinfo.push(field_ArcgisQueryFeatureComputerArea);*/

				$scope.fieldinfo = fieldinfo;//处理字段主键问题

				//处理字段历史展示问题
				var sl = $scope.analysisLayer.selectedRow;
				if (sl == null) return;
				var csid = sl.id;
				if ($scope.gisFields[csid] == null) {
					$scope.gisFields[csid] = {};
				}
				if ($scope.gisFields[csid].showfieldinfo != null) {
					$scope.showfieldinfo = $.extend(true, [], $scope.gisFields[csid].showfieldinfo);
					for (var k = 0; k < $scope.fieldinfo.length; k++) {
						var unfind = true;
						for (var j = 0; j < $scope.showfieldinfo.length; j++) {
							if ($scope.showfieldinfo[j].name == $scope.fieldinfo[k].name) {
								unfind = false;
								break;
							}
						}
						if (unfind) {
							$scope.fieldinfo[k].selected = false;
						}

					}
				} else {
					$scope.showfieldinfo = [];
					for (var k = 0; k < fieldinfo.length; k++) {
						var field = fieldinfo[k];
						if (field.selected) {
							$scope.showfieldinfo.push(field);
						}
					}
					$scope.gisFields[csid].showfieldinfo = $.extend(true, [], $scope.showfieldinfo);
				}
				//$scope.displayResult=true;//显示数据结果

				//启用页面的选中效果方法**********************************

				$scope.getFieldInfo(sl.medname, null, convert, function (feild) {
					var xbattrlst = [];
					var infoTemplate = $scope.setSearchInfo(feild, sl.name);
					for (var k = 0; k < $scope.resultXb.length; k++) {
						var feature = $scope.resultXb[k];
						feature.geometry.spatialReference = $rootScope.gisObject.mapwkid;
						if (!feature.attributes) {
							feature.attributes = {};
						}
						if (!feature.attributes._guid) {
							feature.attributes._guid = $rootScope.getGUID();
						}
						for (var i in feature.attributes) {
							if (feature.attributes[i] === 'Null') {
								feature.attributes[i] = '';
							}
						}
						//收集小班属性
						xbattrlst.push(feature.attributes);
						//TODO 这里需要处理一下
						//$rootScope.addFeatureSelectGraphic(feature, infoTemplate);
						$scope.addGatherFeatureSelectGraphic(feature, infoTemplate);
					}

					// 启用map.graphics的鼠标事件
					$rootScope.gisObject.map.graphics.enableMouseEvents();
					var mouseOverHandle = dojo.connect($rootScope.gisObject.map.graphics, "onMouseOver", function (evt) {
						var graphic = evt.graphic;
						if (!graphic.attributes) {
							return;
						}
						$rootScope.gisObject.map.setMapCursor("pointer");
						if (graphic.attributes.$isFeature && graphic.attributes.$isFeature == true) {
							$rootScope.highFeatureSelectGraphicEx(graphic);
						}
					});
					var mouseOutHandle = dojo.connect($rootScope.gisObject.map.graphics, "onMouseOut", function (evt) {
						var graphic = evt.graphic;
						if (!graphic.attributes) {
							return;
						}
						$rootScope.gisObject.map.setMapCursor("default");
						if (graphic.attributes.$isFeature && graphic.attributes.$isFeature == true) {
							$rootScope.featureSelectGraphicEx(graphic);
						}
					});
					var clickHandle = dojo.connect($rootScope.gisObject.map.graphics, "onClick", function (evt) {
						var graphic = evt.graphic;
						if (!graphic.attributes) {
							return;
						}
						if (graphic.attributes.$isFeature && graphic.attributes.$isFeature == true) {
							$rootScope.showInfoWindowEx(graphic);
						}
					});
					dojo.disconnect(mouseOverHandle);
					dojo.disconnect(mouseOutHandle);
					dojo.disconnect(clickHandle);
				}, function (e) {
					console.log("获取字段值失败");
				});
			});
		};

		/**
		 * 简单feature选中
		 * feature 要素，it 弹窗信息
		 */
		$scope.addGatherFeatureSelectGraphic = function (feature, it) {
			// 默认选中样式
			var symbol = $scope.getGatherInfoFillSyml();
			/*if(feature.geometry.type == "point"){
				  symbol = $rootScope.getDefaultPointSyml();
			}else if(feature.geometry.type == "polyline"){
				  symbol = $rootScope.getDefaultLineSyml();
			}*/
			feature.attributes.$isFeature = true;
			var graphic = new esri.Graphic(feature.geometry, symbol);
			graphic.defaultSymbol = symbol;
			graphic.attributes = feature.attributes;
			graphic.setInfoTemplate(it);
			$rootScope.gisObject.map.graphics.add(graphic);
			return graphic;
		};

        /* 
		 * 定义默认选中样式
		 */
		$scope.getGatherInfoFillSyml = function () {
			// 线样式
			var outlineSyml = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
					$rootScope.getHighLightDefaultStyle().strokeColor.r,
					$rootScope.getHighLightDefaultStyle().strokeColor.g,
					$rootScope.getHighLightDefaultStyle().strokeColor.b,
					$rootScope.getHighLightDefaultStyle().fillOpacity]),
				$rootScope.getHighLightDefaultStyle().strokeWidth);

			/*var selectFillSyml = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID, outlineSyml,
				new dojo.Color([$rootScope.getHighLightDefaultStyle().fillColor.r,
					$rootScope.getHighLightDefaultStyle().fillColor.g,
					$rootScope.getHighLightDefaultStyle().fillColor.b,
					$rootScope.getHighLightDefaultStyle().fillOpacity]));*/
			//处理结果，不显示相关的小班，但是可以点击查看相关小班的详细信息
			var selectFillSyml = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				null, new dojo.Color([
					254,
					0,
					0,
					0]));
			return selectFillSyml;
		};


		/**
		 * 设置查询信息模板
		 */
		$scope.setSearchInfo = function (showfieldinfo, infoTemplateTitle) {
			if (!showfieldinfo) return null;
			//信息模板
			var infoTemplate = new esri.InfoTemplate();
			//设置Title
			var title = infoTemplateTitle;
			if (title == null) {
				title = "小班";
			}
			title = title + "";
			title = title.replace(/~/gm, '$');
			infoTemplate.setTitle(title);
			//设置Content
			var content = '';
			for (var k = 0; k < showfieldinfo.length; k++) {
				var field = showfieldinfo[k];
				if (field.dictionaryName != null && field.dictionaryName != '') {
					content = content + '<tr> <td width="40%" style="text-align: right;" >' + field.aliasName + '</td> <td width="60%" style="text-align: left;">~{' + field.name + '_DESC' + '}</td> </tr>';
				} else {
					content = content + '<tr> <td width="40%" style="text-align: right;" >' + field.aliasName + '</td> <td width="60%" style="text-align: left;">~{' + field.name + '}</td> </tr>';
				}

			}

			var head = '<div class="container"><table width="100%" class="table-b" style="table-layout:fixed">';
			var foot = "</table></div>";
			content = head + content + foot;
			content = content.replace(/~/gm, '$');
			infoTemplate.setContent(content);
			//设置infoWindow的尺寸
			$rootScope.gisObject.map.infoWindow.resize(240, 260);
			return infoTemplate;
		};

		$scope.showInfoWindowAndResize = function (key) {
			$rootScope.showInfoWindow(key);
			var w = 240;
			var h = 260;
			if (w != null && h != null) {
				$rootScope.gisObject.map.infoWindow.resize(w, h);
			};
		};

		$scope.gisFields = {};

		$scope.resetShowField = function (fieldinfo) {
			var showfieldinfo = [];
			for (var k = 0; k < fieldinfo.length; k++) {
				var field = fieldinfo[k];
				if (field.selected) {
					showfieldinfo.push(field);
				}
			}
			$scope.showfieldinfo = showfieldinfo;
			$scope.showSelectField = false;

			var sl = $scope.analysisLayer.selectedRow;
			if (sl == null) return;
			var csid = sl.sid;
			if ($scope.gisFields[csid] == null) {
				$scope.gisFields[csid] = {};
			}
			$scope.gisFields[csid].showfieldinfo = $.extend(true, [], showfieldinfo);
		};

		/**
		 * 全或者反选择字段问题
		 * @param  {[type]} fieldinfo [description]
		 * @param  {[type]} v         [description]
		 * @return {[type]}           [description]
		 */
		$scope.selectAllField = function (fieldinfo, v) {
			for (var k = 0; k < fieldinfo.length; k++) {
				fieldinfo[k].selected = v;
			}
		};

		/**
		 * 初始化arcgis属性查询条件
		 * @param queryForm 查询对象
		 * @param url 地图服务地址
		 * @param ibox 弹窗页面id
		 * @param pagesize 单个页面最大查询结果数
		 * @param idfield 结果主键字段（存在OBJECT字段就不需要再次设置了）
		 */
		$scope.initGisAttributeQueryform = function (queryForm, url, pagesize, idField) {
			if (pagesize == null) {
				pagesize = 3;
			}
			if (idField == null) {
				idField = "OBJECT";
			}
			$rootScope.initAttSearch(queryForm, null);
			$rootScope.gisObject.searchParameter[queryForm].searchPageSize = pagesize;
			$rootScope.gisObject.searchParameter[queryForm].keyName = idField;
			$rootScope.gisObject.searchParameter[queryForm].keyNames = [idField];
			$rootScope.gisObject.searchParameter[queryForm].url = url + "/0";
			$rootScope.gisObject.searchParameter[queryForm].selectFields = ["*"];
		};

		/**
		 * gis中的pagesize记录被选中时的效果
		 */
		$scope.gisListSelectObject = function (list, row) {
			/*if(list==null || list.length<1) return;
			if(row==null) row=list[0];*/
			var selected = !row.selected;
			/*for(var k=0;k<list.length;k++){
				list[k]["selected"]=false;
			};*/
			row["selected"] = selected;
			return;
		}

		/**
		 * 定位功能
		 */
		$scope.gisDirectObject = function (list) {
			var graphics = [];
			for (var k = 0; k < list.length; k++) {
				var f = list[k];
				if (f.selected) {
					graphics.push(f);
					//$rootScope.addFeaturePopGraphic(f,(k+1));
					$rootScope.addFeatureSelectGraphic(f)
				}

			};
			if (graphics.length < 1) {
				$.messager.alert("系统提示", "没有选中的小班");
				return;
			}
			//设置地图视图范围
			var rExtent = $rootScope.getMaxExtent(graphics);
			$rootScope.gisObject.map.setExtent(rExtent);
		};

		/**
		 * 定位到小班位置
		 * @param {Object} row
		 */
		$scope.dirToxb = function (row) {
			var graphics = [];
			graphics.push(row);
			$rootScope.addFeatureSelectGraphic(row);
			var rExtent = $rootScope.getMaxExtent(graphics);
			$rootScope.gisObject.map.setExtent(rExtent);
		};

		$rootScope.onFileUpload = function (fileInfo) {
			$scope.uploaddata = null;
			console.log(fileInfo);

			if (fileInfo != null && fileInfo.graphic != null) {



				var graphic = fileInfo.graphic[0];
				var arcgisGemetrys = null;
				var go = $rootScope.gisObject;
				var srf = null;
				if (go.mapisdlwkid) {
					srf = go.dlwkid.wkid;
				} else {
					srf = go.tywkid.wkid;
				}

				if (graphic.featureType == 'POLYG') {
					arcgisGemetrys = $scope.getArcgisPlogyGeomety(graphic, srf);
				} else if (graphic.featureType == 'LINE') {
					arcgisGemetrys = $scope.getArcgisPolyLinesGeomety(graphic, srf);
				} else if (graphic.featureType == 'POINT') {
					arcgisGemetrys = $scope.getArcgisPointsGeomety(graphic, srf);
				}

				for (var k = 1; k < fileInfo.graphic.length; k++) {
					var temp = fileInfo.graphic[k];
					var tempGeo = null;
					if (temp.featureType == 'POLYG') {
						tempGeo = $scope.getArcgisPlogyGeomety(temp, srf);
					} else if (graphic.featureType == 'LINE') {
						tempGeo = $scope.getArcgisPolyLinesGeomety(temp, srf);
					} else if (graphic.featureType == 'POINT') {
						tempGeo = $scope.getArcgisPointsGeomety(temp, srf);
					}
					if (tempGeo != null && tempGeo[0] != null && tempGeo[0].rings != null /*&& tempGeo[0].rings.length>0*/) {
						/*for(var j=0;j<tempGeo[0].rings.length;j++){
							arcgisGemetrys[]
						}*/
						arcgisGemetrys.push(tempGeo[0]);
					}

				}


				//图形几何校正
				$rootScope.gisObject.geometryService.simplify(arcgisGemetrys, function (simplifiedGeometries) {
					$rootScope.clearGraphics();
					$rootScope.analysisGeometry = simplifiedGeometries[0];
					for (var k = 1; k < simplifiedGeometries.length; k++) {
						if (simplifiedGeometries[k].rings != null && simplifiedGeometries[k].rings.length > 0) {
							for (var j = 0; j < simplifiedGeometries[k].rings.length; j++) {
								$rootScope.analysisGeometry.rings.push(simplifiedGeometries[k].rings[j]);
							}
						}
					}

					var guid = $rootScope.getGUID();
					$rootScope.addAnalysisDefaultGraphic($rootScope.analysisGeometry, guid);
					//设置地图视图范围
					var feature = {};
					feature.geometry = $.extend(true, {}, $rootScope.analysisGeometry);
					var rExtent = $rootScope.getMaxExtent([feature]);
					$rootScope.gisObject.map.setExtent(rExtent);
				}, function (e) {
					$.messager.alert("系统提示", "不能分析,请检查文件中GPS点串格式！");
					return;
				});
			}
		};

    	/**
		* polygon点串转换为arcGis图形，支持多polygon,格式如下 图形与图形之间"_" 同一图形多环";" 点之间"," 同一点经纬度间"
		* "空格 sfr:空间参考
		*/
		$scope.getArcgisPlogyGeomety = function (graphic, srf) {
			// 返回的图形数组
			var goeArr = new Array();

			var points = new Array();
			// 遍历不同图形
			var tGoe = new esri.geometry.Polygon(srf);
			var rings = new Array();
			for (var i = 0; i < graphic.points.length; i++) {

				var ipoint = graphic.points[i];
				p = new esri.geometry.Point(Number(ipoint.x), Number(ipoint.y), srf);
				if (!isNaN(p.x) && !isNaN(p.y)) {
					rings.push(p);
				} else {
					throw new Error("数据格式不正确，请检查坐标！");
				}
			}
			tGoe.addRing(rings);
			goeArr.push(tGoe);
			return goeArr;
		};

		/**
		* polyLine点串转换为arcGis图形，支持多polyLine,格式如下 图形与图形之间"_" 点之间"," 同一点经纬度间" "空格
		* 
		* @param pointStr
		*            点串
		* @param sfr空间参考
		*/
		$scope.getArcgisPolyLinesGeomety = function (graphic, srf) {
			// 返回的图形数组
			var goeArr = new Array();
			//var geoPointArr = pointStr.substr(pointStr.indexOf(":")+1).split("_");
			var tGoe = new esri.geometry.Polyline(srf);
			var points = new Array();
			for (var i = 0; i < graphic.points.length; i++) {

				var ipoint = graphic.points[i];
				p = new esri.geometry.Point(Number(ipoint.x), Number(ipoint.y), srf);
				if (!isNaN(p.x) && !isNaN(p.y)) {
					points.push(p);
				} else {
					throw new Error("数据格式不正确，请检查坐标！");
				}
			}
			tGoe.addPath(points);
			goeArr.push(tGoe);
			return goeArr;
		};

		/**
		 * point点串转换为arcGis图形， 支持多个point, 格式如下 图形与图形之间"_" 点之间"," 同一点经纬度间" "空格
		 * sfr:空间参考
		 */
		$scope.getArcgisPointsGeomety = function (graphic, srf) {
			// 返回的图形数组
			var goeArr = new Array();
			p = new esri.geometry.Point(Number(graphic.x), Number(graphic.x), srf);
			goeArr.push(p);
			return goeArr;
		};

		/*$scope.exportResult=function(){

			$scope.downTest();
			$rootScope.printImage();
		}*/

		$scope.exportResult = function () {
			if ($scope.resultXb == null) {
				$.messager.alert("系统提示", "请先进行分析");
			};
			var template = "sylddcb.html";
			var filename = "使用林地调查表.docx";
			var data = {};
			data.xblst = [];
			data.zbfw_zbx = "";//坐标系统暂时先去掉
			data.zbfw = [];

			var geo = null;
			if ($rootScope.bufferGeomery != null && $rootScope.bufferGeomery.rings != null) {
				geo = $rootScope.bufferGeomery;
			} else {
				geo = $rootScope.analysisGeometry;
			}

			if (geo != null) {
				for (var k = 0; k < geo.rings.length; k++) {
					var kR = geo.rings[k];
					for (var j = 0; j < kR.length; j++) {
						var jR = kR[j];

						var tp = {};
						tp.x = jR[0];
						tp.y = jR[1];

						data.zbfw.push(tp);
					}
				}
			}

			var count_mainji = 0;
			for (var k = 0; k < $scope.resultXb.length; k++) {

				var iattr = $scope.resultXb[k].attributes;


				if (iattr["XIAN_DESC"] == null) {
					iattr["XIAN_DESC"] = "";
				}

				if (iattr["XIANG_DESC"] == null) {
					iattr["XIANG_DESC"] = "";
				}

				if (iattr["CUN_DESC"] == null) {
					iattr["CUN_DESC"] = "";
				}

				if (iattr["DI_JI_HAO"] == null) {
					iattr["DI_JI_HAO"] = "";
				}

				//if(iattr["MIAN_JI"]==null){
				//iattr["MIAN_JI"]="";
				//iattr["MIAN_JI_RC"]="";
				//}else{

				//console.log("面积导出计算：小班号："+iattr["DI_JI_HAO"]);
				//iattr["MIAN_JI_RC"]=Number(iattr["MIAN_JI"])*iattr["Valuepercentage"];

				//iattr["MIAN_JI_RC"]=$rootScope.numformate(iattr["MIAN_JI_RC"],4);
				//console.log(iattr["MIAN_JI"]+"*"+iattr["Valuepercentage"]+"="+iattr["MIAN_JI_RC"]);
				//iattr["MIAN_JI_RC"]=Number(iattr["MIAN_JI"])*iattr["Valuepercentage"];
				//iattr["MIAN_JI_RC"]=$rootScope.numformate(iattr["ArcgisComputerArea"]*100,6);
				//iattr["MIAN_JI_RC"]=iattr["ArcgisComputerArea"]*100;
				//count_mainji=count_mainji+iattr["MIAN_JI_RC"];
				//}
				//面积计算规则20180913
				iattr["MIAN_JI_RC"] = iattr["ArcgisComputerArea"] * 100;
				count_mainji = count_mainji + iattr["MIAN_JI_RC"];

				if (iattr["DI_LEI_DESC"] == null) {
					iattr["DI_LEI_DESC"] = "";
				}

				if (iattr["LD_QS_DESC"] == null) {
					iattr["LD_QS_DESC"] = "";
				}
				if (iattr["BH_DJ_DESC"] == null) {
					iattr["BH_DJ_DESC"] = "";
				}

				if (iattr["SEN_LIN_LB_DESC"] == null) {
					iattr["SEN_LIN_LB_DESC"] = "";
				}

				if (iattr["GLLX_DESC"] == null) {
					iattr["GLLX_DESC"] = "";
				}

				if (iattr["LIN_ZHONG_DESC"] == null) {
					iattr["LIN_ZHONG_DESC"] = "";
				}

				if (iattr["QI_YUAN_DESC"] == null) {
					iattr["QI_YUAN_DESC"] = "";
				}

				if (iattr["ST_GNDJ_DESC"] == null) {
					iattr["ST_GNDJ_DESC"] = "";
				}

				if (iattr["YOU_SHI_SZ_DESC"] == null) {
					iattr["YOU_SHI_SZ_DESC"] = "";
				}

				if (iattr["LING_ZU_DESC"] == null) {
					iattr["LING_ZU_DESC"] = "";
				}

				if (iattr["PJG"] == null) {
					iattr["PJG"] = "";
				}

				if (iattr["PINGJUN_XJ"] == null) {
					iattr["PINGJUN_XJ"] = "";
				}

				if (iattr["YU_BI_DU"] == null) {
					iattr["YU_BI_DU"] = "";
				}
				if (iattr["HUO_LMGQXJ"] == null) {
					iattr["HUO_LMGQXJ"] = "";
				}

				if (iattr["XB_XJ"] == null) {
					iattr["XB_XJ"] = "";
					iattr["XB_XJ_RC"] = "";
				} else {
					iattr["XB_XJ_RC"] = Number(iattr["XB_XJ"]) * iattr["Valuepercentage"];

				}

				if (iattr["MEI_GQ_ZS"] == null) {
					iattr["MEI_GQ_ZS"] = "";
				}
				$scope.getRelatedFw(iattr);
				data.xblst.push(iattr);
			}
			data.MIAN_JI_COUNT = count_mainji;
			$scope.toExcel(template, data, filename);
		};
		
		$scope.getRelatedFw=function(iattr){
			var tempid=iattr["OBJECTID"];
			iattr["yzsjfw"]=[];
			var templist=$rootScope.getAlysisFeaturesResult();
			if(templist!=null){
				for(var k=0;k<templist.length;k++){
					var itemp=templist[k];
					if(itemp.attributes["OBJECTID"]==tempid){
						var value = itemp.attributes["DI_LEI"];
						//非林业部门管理林地和非林地，其中20表示非林业部门管理林地
						var gllx = itemp.attributes["GLLX"];
						if ("20" == gllx || 20 == gllx) continue;
						if ("0200" == value) {
							continue;
						}
						var itempfw=$scope.getRelateGeo(itemp.geometry);
						if(itempfw!=null && itempfw.length>0){
							iattr["yzsjfw"].push(itempfw);
						}
					}
				}
			}
		};
		
		/**
		 * 坐标范围
		 * @param {Object} geo
		 */
		$scope.getRelateGeo=function(geo){
			var tempzbfw=[];
			if(geo==null) return null;
			for (var k = 0; k < geo.rings.length; k++) {
				var kR = geo.rings[k];
				for (var j = 0; j < kR.length; j++) {
					var jR = kR[j];
					var tp = {};
					tp.x = jR[0];
					tp.y = jR[1];
					tempzbfw.push(tp);
				}
			}
			return tempzbfw;
		};

		$scope.toExcel = function (template, data, filename) {
			data = $rootScope.toJSONStr(data);
			var url = getServerBaseUrl() + '/print/HtmltoWord';
			var form = $("<form></form>").attr("action", url).attr("method", "post");
			form.append($("<input></input>").attr("type", "hidden").attr("name", "template").attr("value", template));
			form.append($("<input></input>").attr("type", "hidden").attr("name", "filename").attr("value", filename));
			form.append($("<input></input>").attr("type", "hidden").attr("name", "data").attr("value", data));
			form.append($("<input></input>").attr("type", "hidden").attr("name", "pageLocation").attr("value", "true"));
			form.appendTo('body').submit().remove();
		};

		/**
		 * 清空所有图形处理
		 */
		$scope.clearAllGeos = function () {
			$rootScope.clearGraphics();
			$rootScope.analysisGeometry = null;
		};

	}]);
});